import React, { useState } from 'react';
import { Col, Row, Icon, Popover, List, Input } from 'antd';
import styles from './FlowVariablesSelector.less';


const FlowVariablesSelectorPopover = (props) => {
  const [visible, setVisible] = useState(false);

  const { onSelect } = props;

  const onSelectWrapper = (...args) => {
    onSelect(...args);
    setVisible(false);
  }

  return (
    <Popover
      placement="bottomRight"
      title="插入变量"
      content={<FlowVariablesSelector {...{...props, onSelect: onSelectWrapper}} />}
      trigger="click"
      visible={visible}
      onVisibleChange={setVisible}
    >
      <Icon type="plus-circle" theme="filled" className={styles.icon} />
    </Popover>
  );
}

const FlowVariablesSelector = (props) => {
  const { variables, onSelect } = props;
  const [filter, setFilter] = useState(null);

  let listSource = variables || [];
  if (filter) {
    listSource = listSource.filter(({ code, name }) => (
      code.indexOf(filter) > -1 || name.indexOf(filter) > -1
    ))
  }

  return (
    <Row className={styles.root}>
      <div>
        <Input
          placeholder="请输入"
          onChange={e => setFilter(e.target.value)}
        />
      </div>
      <List
        className={styles.listRoot}
        itemLayout="vertical"
        dataSource={listSource}
        renderItem={item => {
          const { code, name, variableSource, formName } = item;
          return (
            <List.Item>
              <Row
                className={styles.container}
                onClick={() => {
                  onSelect(item)
                }}
              >
                <Row
                  className={styles.title}
                  onClick={() => {
                    onSelect(item)
                  }}
                >
                  {name}
                </Row>
                <Row type="flex" justify="space-between">
                  <Col className={styles.code}>
                    {code}
                  </Col>
                  <Col className={styles.extra}>
                    {variableSource === 'form' ? `从【${formName}表单】获取` : '手动添加'}
                  </Col>
                </Row>
              </Row>
            </List.Item>
          );
        }}
      />
    </Row>
  )
}

export { FlowVariablesSelector };
export default FlowVariablesSelectorPopover;